﻿#include "comfunc.h"
#include <QDateTime>
#include <sys/timeb.h>
#include <windows.h>
#include <WinSock.h>
#include <time.h>
using namespace std;
typedef __int64 int64_t;
#define EPOCHFILETIME   (116444736000000000UL)

LARGE_INTEGER ComFunc::m_OrderStartTime;
int           ComFunc::m_iLogIndex;
QFile*        ComFunc::m_LogFile;
int           ComFunc::m_iOrderRef = QTime::currentTime().toString("hms").toInt();
QMutex        ComFunc::m_mutex;

ComFunc::ComFunc()
{

}
ComFunc::~ComFunc(){

}

void ComFunc::LogFileInit(){
    QDateTime qDateTime = QDateTime::currentDateTime();
    QString   strLogName = qDateTime.toString("yyyyMMdd") + ".txt";
    m_LogFile = new QFile(strLogName);
    m_LogFile->open(QIODevice::WriteOnly | QIODevice::Append);
}
void ComFunc::LogFileRelease(){
    m_LogFile->close();
    delete m_LogFile;
}

///判断Qstring中是不是纯数字
int ComFunc::isDigitStr(QString src){
    QByteArray ba = src.toLatin1();//QString 转换为 char*
    const char *s = ba.data();

    while(*s && *s>='0' && *s<='9')
        s++;

    if (*s){ //不是纯数字
        return -1;
    }else{ //纯数字
        return 0;
    }
}

QString ComFunc::GetCofcoStatusName(int iStatus)
{
	QString sStatus;
	switch(iStatus)
	{
	case 1 :{sStatus=QStringLiteral("已报"); break;}
	case 2 :{sStatus=QStringLiteral("部成"); break;}	
	case 3 :{sStatus=QStringLiteral("完成"); break;}
	case 4 :{sStatus=QStringLiteral("已撤"); break;}		
	default: {sStatus=QStringLiteral("未知"); break;};
	}
	return sStatus;
}

QString ComFunc::GetCofcoOrderType(int iType)
{
	QString sType;
	switch(iType)
	{
	case 1 :{sType=QStringLiteral("均价"); break;}
	case 2 :{sType=QStringLiteral("套利"); break;}	
	case 3 :{sType=QStringLiteral("移仓"); break;}	
	default: {sType=QStringLiteral("未知"); break;};
	}
	return sType;
}

QString ComFunc::GetBSName( int iBS)
{
	QString sBS;
	switch(iBS)
	{
	case 1 :{sBS=QStringLiteral("买入"); break;}
	case 2 :{sBS=QStringLiteral("卖出"); break;}				 
	default: {sBS=QStringLiteral("未知"); break;};
	}
	return sBS;
}

QString ComFunc::GetOCName( int iOC)
{
	QString sOC;
	switch(iOC)
	{
	case 1 :sOC=QStringLiteral("开仓"); break;
	case 2 :sOC=QStringLiteral("平仓"); break;
	case 4 :sOC=QStringLiteral("平今仓"); break;
	default: sOC=QStringLiteral("未知"); break;
	}
	return sOC;
}

QString ComFunc::GetHedgeType( int cHedge)
{
	QString csHedge;
	switch(cHedge)
	{
	case 0 :{csHedge=QStringLiteral("投机"); break;}
	case 1 :{csHedge=QStringLiteral("套保"); break;}				 
	default: {csHedge=QStringLiteral("投机"); break;};
	}
	return csHedge;
}

QString ComFunc::GetCurrTime()
{
    LARGE_INTEGER litmp;
    QueryPerformanceFrequency(&litmp);
    double dTimeFre = (double)litmp.QuadPart;//返回硬件支持的高精度计数器的频率(每秒钟的CPU Tick数)

    LARGE_INTEGER time;
    QueryPerformanceCounter(&time);//返回高精度计数器的计数值
    double time_elapsed = ((double)(time.QuadPart - m_OrderStartTime.QuadPart)/ dTimeFre)*1000;//毫秒级别

    QString currtime = QTime::currentTime().toString("hh:mm:ss");
    //SYSTEMTIME sys;
    //GetLocalTime( &sys );
    //QString currtime = QString::number(sys.wHour)+":" + QString::number(sys.wMinute) +":"+ QString::number(sys.wSecond) +"."+ QString::number(sys.wMilliseconds);

    //QString CurTime1 = QString::fromStdString(GetDateString());

    //return currtime + " " + CurTime1 + " "+QString::number(time_elapsed,'g',5);
    return currtime + " "+QString::number(time_elapsed,'f',5);
}
//将微秒数时间戳格式化成"yyyy-MM-dd hh:mm:ss zzz uuu"
string ComFunc::GetDateString() {
    time_t timeUs = GetHighAccuracyMicros();
    char str[100], strMicro[10];
    memset(strMicro, 0, 10);
    struct tm stTm;
    int microSecond = timeUs % 1000;
    int milliSecond = timeUs / 1000 % 1000;
    time_t timeSecond = timeUs / 1000 / 1000;
    stTm = *localtime(&timeSecond);
    strftime(str, sizeof(str), "%Y-%m-%d %H:%M:%S", &stTm);
    sprintf(strMicro, " %03d %03d", milliSecond, microSecond);
    strcat(str, strMicro);
    return str;
}

LARGE_INTEGER ComFunc::getFILETIMEoffset()
{
    SYSTEMTIME s;
    FILETIME f;
    LARGE_INTEGER t;

    s.wYear = 1970;
    s.wMonth = 1;
    s.wDay = 1;
    s.wHour = 0;
    s.wMinute = 0;
    s.wSecond = 0;
    s.wMilliseconds = 0;
    SystemTimeToFileTime(&s, &f);
    t.QuadPart = f.dwHighDateTime;
    t.QuadPart <<= 32;
    t.QuadPart |= f.dwLowDateTime;
    return (t);
}
int ComFunc::clock_gettime(int X, struct timeval *tv)
{
    LARGE_INTEGER           t;
    FILETIME            f;
    double                  microseconds;
    LARGE_INTEGER    offset;
    double           frequencyToMicroseconds;
    BOOL             usePerformanceCounter = 0;


    LARGE_INTEGER performanceFrequency;
    usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);
    if (usePerformanceCounter) {
        QueryPerformanceCounter(&offset);
        frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;
    } else {
        offset = getFILETIMEoffset();
        frequencyToMicroseconds = 10.;
    }

    if (usePerformanceCounter)  {
        QueryPerformanceCounter(&t);
    } else {
        GetSystemTimeAsFileTime(&f);
        t.QuadPart = f.dwHighDateTime;
        t.QuadPart <<= 32;
        t.QuadPart |= f.dwLowDateTime;
    }

    t.QuadPart -= offset.QuadPart;
    microseconds = (double)t.QuadPart / frequencyToMicroseconds;
    t.QuadPart = microseconds;
    tv->tv_sec = t.QuadPart / 1000000;
    tv->tv_usec = t.QuadPart % 1000000;
    return (0);
}
// 获取系统的当前时间，单位微秒(us)
__int64 ComFunc::GetHighAccuracyMicros()
{    // 从1601年1月1日0:0:0:000到1970年1月1日0:0:0:000的时间(单位100ns)
    FILETIME ft;
    LARGE_INTEGER li;
    __int64 initMicrosecond = 0;

    GetSystemTimeAsFileTime(&ft);
    li.LowPart = ft.dwLowDateTime;
    li.HighPart = ft.dwHighDateTime;
    // 从1970年1月1日0:0:0:000到现在的微秒数(UTC时间)
    initMicrosecond = (li.QuadPart - EPOCHFILETIME) /10;

    struct timeval stime;
    clock_gettime(0, &stime);
    int64_t cur_usec = initMicrosecond+stime.tv_sec*1000000+stime.tv_usec;
    return cur_usec ;
}
//报单回报Message输出
QString  ComFunc::OutputInfoMessage(int entrustNo,const char* contractCode, const char* entrustRef, char status){
    m_iLogIndex++;

    QString strMessage = "";
    strMessage = ComFunc::GetCurrTime() + QStringLiteral(" 报单回报 ")
                            + QStringLiteral("合约代码:") + QString(contractCode) + " "
                            + "OrderRef:"+ QString::number(m_iOrderRef) + " "
                            + "OrderLocalID:" + QString::number(entrustNo)+" ";

    //状态
    QString strStatus = "";
    switch(status){
    case    '0':	strStatus = QStringLiteral("未报"); break;
    case 	'1':	strStatus = QStringLiteral("待报");break;
    case 	'2':	strStatus = QStringLiteral("已报");break;
    case 	'3':	strStatus = QStringLiteral("已报待撤");break;
    case 	'4':	strStatus = QStringLiteral("部成待撤");break;
    case 	'5':	strStatus = QStringLiteral("部撤");break;
    case 	'6':	strStatus = QStringLiteral("已撤");break;
    case 	'7':	strStatus = QStringLiteral("部成");break;
    case 	'8':	strStatus = QStringLiteral("已成");break;
    case 	'9':	strStatus = QStringLiteral("废单");break;
    case 	'C':	strStatus = QStringLiteral("撤单已提交");break;
    case 	'E':	strStatus = QStringLiteral("报单已提交");break;
    default:        strStatus = QString(status);break;
    }

    strMessage = strMessage + strStatus+ " ";
    strMessage = strMessage + QStringLiteral("序号:") + QString::number(m_iLogIndex);

    m_mutex.lock();
    QTextStream text_stream(m_LogFile);
    text_stream << strMessage << "\r\n";
    m_LogFile->flush();
    m_mutex.unlock();

    return ComFunc::GetCurrTime();
}
//提交报单委托的时候 打印Log
void  ComFunc::OutputInsertMessage(const char* contract_code,const char* orderRef){
    QueryPerformanceCounter(&m_OrderStartTime);//返回高精度计数器的计数值
    m_iLogIndex = 1;//Log的序号置为1
    m_iOrderRef ++;

    QString strMessage = "\r\n" + ComFunc::GetCurrTime() + QStringLiteral(" 报单委托 ")
                        + QStringLiteral("合约代码:") + QString(contract_code) + " "
                        + "OrderRef:"+ QString::number(m_iOrderRef) +" "
                        + QStringLiteral("序号:") + QString::number(m_iLogIndex);

    m_mutex.lock();
    QTextStream text_stream(m_LogFile);
    text_stream << strMessage << "\r\n";
    m_LogFile->flush();
    m_mutex.unlock();
}
//成交回报
void  ComFunc::OutputSuccessMessage(){
    m_iLogIndex++;
    /*QString strMessage = ComFunc::GetCurrTime() + QStringLiteral(" 成交回报 ")
            + QStringLiteral("合约代码:") + QString(pTrade->InstrumentID) + " "
            + "OrderRef:"+ QString(pTrade->OrderRef) + " OrderLocalID:" + QString(pTrade->OrderLocalID)+" "
            + QStringLiteral("成交时间:")+ QString(pTrade->TradeTime) + " "
            + QStringLiteral("成交价格:")+ QString::number(pTrade->Price,'f')+ " "
            + QStringLiteral("序号:") + QString::number(m_iLogIndex);
    m_mutex.lock();
	QTextStream text_stream(LogFile);
	text_stream << strMessage << "\r\n";
    m_LogFile->flush();
    m_mutex.unlock();*/
}
void  ComFunc::OutputErrMessage(QString msg){
    QString strMessage = ComFunc::GetCurrTime() +" ERROR " + msg;

    m_mutex.lock();
    QTextStream text_stream(m_LogFile);
    text_stream << strMessage << "\r\n";
    m_LogFile->flush();
    m_mutex.unlock();
}
